<template>
  <div class="menu-list">
    <el-card class="menu-card">
      <template #header>
        <div class="card-header">
          <span>菜单管理</span>
          <el-button type="primary" @click="handleAdd">添加菜单</el-button>
        </div>
      </template>

      <el-table
        :data="menuTreeData"
        v-loading="loading"
        row-key="id"
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="name" label="菜单名称" width="200">
          <template #default="scope">
            <span :style="{ 'margin-left': scope.row.level * 20 + 'px' }">
              {{ scope.row.name }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="菜单标题" width="150" />
        <el-table-column prop="path" label="路由路径" width="150" />
        <el-table-column prop="component" label="组件路径" show-overflow-tooltip />
        <el-table-column prop="icon" label="图标" width="100">
          <template #default="scope">
            <el-icon v-if="scope.row.icon">
              <component :is="scope.row.icon" />
            </el-icon>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.type === 1">目录</el-tag>
            <el-tag v-else-if="scope.row.type === 2" type="success">菜单</el-tag>
            <el-tag v-else-if="scope.row.type === 3" type="warning">按钮</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="order" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleAddChild(scope.row)">添加下级</el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="small"
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 1 ? '禁用' : '启用' }}
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.row)"
              :disabled="scope.row.parentId === 0"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑菜单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="menuFormRef"
        :model="menuForm"
        :rules="menuRules"
        label-width="100px"
      >
        <el-form-item label="上级菜单" prop="parentId">
          <el-tree-select
            v-model="menuForm.parentId"
            :data="menuOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            node-key="id"
            placeholder="请选择上级菜单"
            check-strictly
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="menuForm.type">
            <el-radio :label="1">目录</el-radio>
            <el-radio :label="2">菜单</el-radio>
            <el-radio :label="3">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="menuForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="菜单标题" prop="title">
          <el-input v-model="menuForm.title" placeholder="请输入菜单标题" />
        </el-form-item>
        <el-form-item v-if="menuForm.type !== 3" label="路由路径" prop="path">
          <el-input v-model="menuForm.path" placeholder="请输入路由路径" />
        </el-form-item>
        <el-form-item v-if="menuForm.type === 2" label="组件路径" prop="component">
          <el-input v-model="menuForm.component" placeholder="请输入组件路径" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="menuForm.icon" placeholder="请输入图标名称" />
        </el-form-item>
        <el-form-item label="权限标识" prop="permission">
          <el-input v-model="menuForm.permission" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="排序" prop="order">
          <el-input-number v-model="menuForm.order" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="menuForm.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave" :loading="saveLoading">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { Menu, MenuTree, CreateMenuRequest, UpdateMenuRequest } from '@/types/api/menu'
import { menuApi } from '@/api/modules/menu'
import { formUtils } from '@/utils'

// 表格相关
const loading = ref(false)
const menuTreeData = ref<MenuTree[]>([])

// 菜单选项（用于上级菜单选择）
const menuOptions = ref<MenuTree[]>([
  {
    id: 0,
    parentId: 0,
    name: '顶级菜单',
    path: '',
    component: '',
    icon: '',
    title: '顶级菜单',
    order: 0,
    status: 1,
    type: 1,
    permission: '',
    createdAt: '',
    updatedAt: '',
    children: []
  }
])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const saveLoading = ref(false)
const menuFormRef = ref()
const currentMenuId = ref(0)

// 表单数据
const menuForm = reactive({
  parentId: 0,
  name: '',
  path: '',
  component: '',
  icon: '',
  title: '',
  order: 0,
  status: 1,
  type: 2,
  permission: ''
})

// 表单验证规则
const menuRules = {
  parentId: [
    { required: true, message: '请选择上级菜单', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入菜单标题', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入路由路径', trigger: 'blur' }
  ],
  component: [
    { required: true, message: '请输入组件路径', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择菜单类型', trigger: 'change' }
  ]
}

// 获取菜单列表
const getMenuList = async () => {
  loading.value = true
  try {
    const response = await menuApi.getMenuList()
    menuTreeData.value = response.data.data
    // 构建菜单选项（用于上级菜单选择）
    menuOptions.value = [
      {
        id: 0,
        parentId: 0,
        name: '顶级菜单',
        path: '',
        component: '',
        icon: '',
        title: '顶级菜单',
        order: 0,
        status: 1,
        type: 1,
        permission: '',
        createdAt: '',
        updatedAt: '',
        children: response.data.data
      }
    ]
  } catch (error) {
    ElMessage.error('获取菜单列表失败')
  } finally {
    loading.value = false
  }
}

// 添加菜单
const handleAdd = () => {
  dialogTitle.value = '添加菜单'
  isEdit.value = false
  dialogVisible.value = true
  // 重置表单
  Object.assign(menuForm, {
    parentId: 0,
    name: '',
    path: '',
    component: '',
    icon: '',
    title: '',
    order: 0,
    status: 1,
    type: 2,
    permission: ''
  })
}

// 添加下级菜单
const handleAddChild = (row: Menu) => {
  dialogTitle.value = '添加下级菜单'
  isEdit.value = false
  dialogVisible.value = true
  currentMenuId.value = 0
  // 设置父级ID
  Object.assign(menuForm, {
    parentId: row.id,
    name: '',
    path: '',
    component: '',
    icon: '',
    title: '',
    order: 0,
    status: 1,
    type: 2,
    permission: ''
  })
}

// 编辑菜单
const handleEdit = (row: Menu) => {
  dialogTitle.value = '编辑菜单'
  isEdit.value = true
  dialogVisible.value = true
  currentMenuId.value = row.id
  // 填充表单数据
  Object.assign(menuForm, {
    parentId: row.parentId,
    name: row.name,
    path: row.path,
    component: row.component,
    icon: row.icon,
    title: row.title,
    order: row.order,
    status: row.status,
    type: row.type,
    permission: row.permission
  })
}

// 启用/禁用菜单
const handleToggleStatus = async (row: Menu) => {
  try {
    await menuApi.updateMenuStatus(row.id, {
      status: row.status === 1 ? 0 : 1
    })
    ElMessage.success(`${row.status === 1 ? '禁用' : '启用'}成功`)
    await getMenuList()
  } catch (error) {
    ElMessage.error(`${row.status === 1 ? '禁用' : '启用'}失败`)
  }
}

// 删除菜单
const handleDelete = (row: Menu) => {
  formUtils.handleDeleteConfirm(`菜单 "${row.name}"`, async () => {
    await menuApi.deleteMenu(row.id)
    getMenuList()
  }, {
    successMessage: '删除成功',
    errorMessage: '删除失败'
  })
}

// 保存菜单信息
const handleSave = async () => {
  if (!menuFormRef.value) return

  await menuFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      saveLoading.value = true
      try {
        // 根据菜单类型处理必填字段
        if (menuForm.type === 1) {
          // 目录类型不需要组件路径
          menuForm.component = ''
        } else if (menuForm.type === 3) {
          // 按钮类型不需要路由路径和组件路径
          menuForm.path = ''
          menuForm.component = ''
        }

        if (isEdit.value) {
          // 编辑菜单
          const updateData: UpdateMenuRequest = {
            parentId: menuForm.parentId,
            name: menuForm.name,
            path: menuForm.path,
            component: menuForm.component,
            icon: menuForm.icon,
            title: menuForm.title,
            order: menuForm.order,
            status: menuForm.status,
            type: menuForm.type,
            permission: menuForm.permission
          }
          await menuApi.updateMenu(currentMenuId.value, updateData)
          ElMessage.success('更新成功')
        } else {
          // 添加菜单
          const createData: CreateMenuRequest = {
            parentId: menuForm.parentId,
            name: menuForm.name,
            path: menuForm.path,
            component: menuForm.component,
            icon: menuForm.icon,
            title: menuForm.title,
            order: menuForm.order,
            status: menuForm.status,
            type: menuForm.type,
            permission: menuForm.permission
          }
          await menuApi.createMenu(createData)
          ElMessage.success('添加成功')
        }
        dialogVisible.value = false
        await getMenuList()
      } catch (error: any) {
        ElMessage.error(error.message || (isEdit.value ? '更新失败' : '添加失败'))
      } finally {
        saveLoading.value = false
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  formUtils.resetForm(menuFormRef.value, menuForm, {
    parentId: 0,
    name: '',
    path: '',
    component: '',
    icon: '',
    title: '',
    order: 0,
    status: 1,
    type: 2,
    permission: ''
  })
}

// 初始化
onMounted(() => {
  getMenuList()
})
</script>

<style scoped lang="scss">
.menu-list {
  .menu-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
